package com.classic.core.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import com.baidu.mobstat.SendStrategyEnum;
import com.baidu.mobstat.StatService;
import com.classic.core.fragment.BaseFragment;
import com.classic.core.interfaces.I_Activity;
import com.classic.core.interfaces.I_Register;
import com.classic.core.utils.KeyBoardUtil;
import com.classic.core.utils.SharedPreferencesUtil;
import com.classic.core.utils.StringUtil;

import cn.jpush.android.api.JPushInterface;

/**
 * Activity父类
 *
 * @author 续写经典
 * @date 2015/11/7
 */
public abstract class BaseActivity extends AppCompatActivity
        implements View.OnClickListener, I_Activity, I_Register {

    /**
     * Activity状态
     */
    public int activityState = DESTROY;
    protected BaseFragment currentFragment;
    protected Activity activity;
    private SharedPreferencesUtil spUtil;
    public static final String SP_NAME = "firstConfig";

    public static boolean isForeground = false;
    private MessageReceiver mMessageReceiver;
    public static final String MESSAGE_RECEIVED_ACTION = "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION";
    public static final String KEY_TITLE = "title";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_EXTRAS = "extras";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity = this;
        initPre();
        BaseActivityStack.getInstance().addActivity(this);
        setContentView(getLayoutResId());
        spUtil = new SharedPreferencesUtil(this, SP_NAME);
        final String simpleName = this.getClass().getSimpleName();
        if (spUtil.getBooleanValue(simpleName, true)) {
            onFirst();
            spUtil.putBooleanValue(simpleName, false);
        }
        initInstanceState(savedInstanceState);
        initData();
        initToolbar();
        initView();
        register();
        init();
        registerMessageReceiver();
    }

    // 初始化 JPush。如果已经初始化，但没有登录成功，则执行重新登录。
    private void init() {
        JPushInterface.init(getApplicationContext());

        StatService.setAppKey("49f126407d");
        StatService.setSessionTimeOut(30);
        // setOn也可以在AndroidManifest.xml文件中填写，BaiduMobAd_EXCEPTION_LOG，打开崩溃错误收集，默认是关闭的
        StatService.setOn(this, StatService.EXCEPTION_LOG);
        /*
         * 设置启动时日志发送延时的秒数<br/> 单位为秒，大小为0s到30s之间<br/> 注：请在StatService.setSendLogStrategy之前调用，否则设置不起作用
         *
         * 如果设置的是发送策略是启动时发送，那么这个参数就会在发送前检查您设置的这个参数，表示延迟多少S发送。<br/> 这个参数的设置暂时只支持代码加入，
         * 在您的首个启动的Activity中的onCreate函数中使用就可以。<br/>
         */
        StatService.setLogSenderDelayed(0);
        /*
         * 用于设置日志发送策略<br /> 嵌入位置：Activity的onCreate()函数中 <br />
         *
         * 调用方式：StatService.setSendLogStrategy(this,SendStrategyEnum. SET_TIME_INTERVAL, 1, false); 第二个参数可选：
         * SendStrategyEnum.APP_START SendStrategyEnum.ONCE_A_DAY SendStrategyEnum.SET_TIME_INTERVAL 第三个参数：
         * 这个参数在第二个参数选择SendStrategyEnum.SET_TIME_INTERVAL时生效、 取值。为1-24之间的整数,即1<=rtime_interval<=24，以小时为单位 第四个参数：
         * 表示是否仅支持wifi下日志发送，若为true，表示仅在wifi环境下发送日志；若为false，表示可以在任何联网环境下发送日志
         */
        StatService.setSendLogStrategy(this, SendStrategyEnum.SET_TIME_INTERVAL, 1, false);
        // 调试百度统计SDK的Log开关，可以在Eclipse中看到sdk打印的日志，发布时去除调用，或者设置为false
        StatService.setDebugOn(true);

    }

    public void registerMessageReceiver() {
        mMessageReceiver = new MessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(MESSAGE_RECEIVED_ACTION);
        registerReceiver(mMessageReceiver, filter);
    }

    public class MessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
                String messge = intent.getStringExtra(KEY_MESSAGE);
                String extras = intent.getStringExtra(KEY_EXTRAS);
                StringBuilder showMsg = new StringBuilder();
                showMsg.append(KEY_MESSAGE + " : " + messge + "\n");
                if (!StringUtil.isEmpty(extras)) {
                    showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
                }
                //setCostomMsg(showMsg.toString());
            }
        }
    }

    @Override
    public void initPre() {
    }

    @Override
    public void onFirst() {
    }

    @Override
    public void initInstanceState(Bundle savedInstanceState) {
    }

    @Override
    public void initData() {
    }

    @Override
    public void initToolbar() {
    }

    @Override
    public void initView() {
    }

    @Override
    public void viewClick(View v) {
    }

    @Override
    public void showProgress() {
    }

    @Override
    public void hideProgress() {
    }

    @Override
    public void register() {
    }

    @Override
    public void unRegister() {
    }

    @Override
    public void onClick(View v) {
        viewClick(v);
    }

    @Override
    public void skipActivity(Activity aty, Class<?> cls) {
        startActivity(aty, cls);
        aty.finish();
    }

    @Override
    public void skipActivity(Activity aty, Intent it) {
        startActivity(aty, it);
        aty.finish();
    }

    @Override
    public void skipActivity(Activity aty, Class<?> cls, Bundle extras) {
        startActivity(aty, cls, extras);
        aty.finish();
    }

    @Override
    public void startActivity(Activity aty, Class<?> cls) {
        Intent intent = new Intent();
        intent.setClass(aty, cls);
        aty.startActivity(intent);
    }

    @Override
    public void startActivity(Activity aty, Intent it) {
        aty.startActivity(it);
    }

    @Override
    public void startActivity(Activity aty, Class<?> cls, Bundle extras) {
        Intent intent = new Intent();
        intent.putExtras(extras);
        intent.setClass(aty, cls);
        aty.startActivity(intent);
    }

    /**
     * 用Fragment替换视图
     *
     * @param resView        将要被替换掉的视图
     * @param targetFragment 用来替换的Fragment
     */
    public void changeFragment(int resView, BaseFragment targetFragment) {
        if (targetFragment.equals(currentFragment)) {
            return;
        }
        android.support.v4.app.FragmentTransaction transaction = getSupportFragmentManager()
                .beginTransaction();
        if (!targetFragment.isAdded()) {
            transaction.add(resView, targetFragment, targetFragment.getClass()
                    .getName());
        }
        if (targetFragment.isHidden()) {
            transaction.show(targetFragment);
            targetFragment.onChange();
        }
        if (currentFragment != null
                && currentFragment.isVisible()) {
            transaction.hide(currentFragment);
            currentFragment.onHidden();
        }
        currentFragment = targetFragment;
        transaction.commit();
    }

    @Override
    protected void onResume() {
        super.onResume();
        isForeground = true;
        StatService.onResume(this);
        activityState = RESUME;
    }

    @Override
    protected void onPause() {
        super.onPause();
        isForeground = false;
        StatService.onPause(this);
        activityState = PAUSE;
    }

    @Override
    protected void onStop() {
        super.onStop();
        activityState = STOP;
    }

    @Override
    protected void onDestroy() {
        unRegister();
        unregisterReceiver(mMessageReceiver);
        super.onDestroy();
        activityState = DESTROY;
        BaseActivityStack.getInstance().finishActivity(this);
    }

    @Override
    public void finish() {
        KeyBoardUtil.hide(getWindow().getDecorView());
        super.finish();
    }

}
